<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\Env;

class Area extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * @var \app\common\model\Area
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\common\model\Area();
    }

    public function all()
    {
        $prefix = Env::get('prefix.prefix', 'meet');

        $cache = Cache::get($prefix . '_all_area');

        if (!$cache) {
            $city_list = $this->model->where('level', '=', 2)->field('id,pid,name')->select();

            $new_city_list = [];

            foreach ($city_list as $k => $v) {
                $v['area'] = $this->model->where('pid', '=', $v['id'])->field('id,pid,name')->select();

                $new_city_list[$v['pid']][] = $v;
            }

            $list = $this->model->where('level', '=', 1)->field('id,name')->select();

            foreach ($list as $key => $value) {
                $value['city'] = $new_city_list[$value['id']];
            }

            Cache::set($prefix . '_all_area', $list);
        } else {
            $list = $cache;
        }

        $this->success('', ['list' => $list]);
    }
}